﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using PreviewDemo;

namespace USV_Ground_Monitor
{
    public partial class Form1 : Form
    {
        #region 浮标串口变量
        //定义显示变量
        private string average_waveHeight = "000.000";
        private string average_period = "000.000";
        private string one_third_waveHeight = "000.000";
        private string one_third_period = "000.000";
        private string one_tenth_waveHeight = "000.000";
        private string one_tenth_period = "000.000";
        private string max_waveHeight = "000.000";
        private string max_period = "000.000";
        //定义是否强制滚动变量
        private bool is_auto_scroll = true;
        //定义截取字符串功能
        private bool start_add = false;//开始添加标志位
        private bool start_true = false;//开头正确标志位
        private bool end_true = false;//结尾正确标志位
        private bool start_analaze = false;//开始分析标志位
        private string data = "";//定义字符串的内容
        #endregion
        //定义窗体的长和宽，用于控件自适应
        private float X;//定义宽度
        private float Y;//定义高度
        #region 摄像头变量
        public int m_lUserID_an = -1;//这个变量可能会有问题，因为是我自己添加的
        public int m_lRealHandle_an = -1;//这个变量可能会有问题，因为是我自己添加的
        public int m_lChannel_an = -1;//这个变量可能会有问题，因为是我自己添加的
        private bool m_bInitSDK = false;
        private uint[] iLastErr = new uint[2] { 0, 0 };
        private Int32[] m_lUserID = new Int32[2] { -1, -1 };
        private Int32[] m_lRealHandle = new Int32[2] { -1, -1 };
        private bool[] m_bRecord = new bool[2] { false, false };
        private string str;
        #endregion
        public Form1()//Form1的构造函数，用于初始化
        {
            InitializeComponent();
            UpdateTextBoxes();
            SerialPort_init();
            RefreshPortList();

            //以下是摄像头部分
            m_bInitSDK = CHCNetSDK.NET_DVR_Init();

            if (m_bInitSDK == false)
            {
                MessageBox.Show("NET_DVR_Init error!");

            }
            else
            {
                // 获取项目的根目录
                string projectDirectory = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;

                // 构建log文件夹的路径
                string logDirectory = Path.Combine(projectDirectory, "log");

                // 确保log文件夹存在
                if (!Directory.Exists(logDirectory))
                {
                    Directory.CreateDirectory(logDirectory);
                }

                // 保存SDK日志
                CHCNetSDK.NET_DVR_SetLogToFile(3, logDirectory, true);
            }
            //
            // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
            //
        }
        #region 自适应放大
        private void setTag(Control cons)//用于获取控件的大小和字体大小，我从网上炒的
        {
            foreach (Control con in cons.Controls)
            {
                con.Tag = con.Width + ":" + con.Height + ":" + con.Left + ":" + con.Top + ":" + con.Font.Size;
                if (con.Controls.Count > 0)
                    setTag(con);
            }
        }
        private void setControls(float newx, float newy, Control cons)//用于设定在全新的窗口大小情况下的控件的大小和字体大小，我从网上炒的
        {
            foreach (Control con in cons.Controls)
            {
                if (con.Tag == null)
                    continue;
                string[] mytag = con.Tag.ToString().Split(new char[] { ':' });
                float a = System.Convert.ToSingle(mytag[0]) * newx;
                con.Width = (int)a;
                a = System.Convert.ToSingle(mytag[1]) * newy;
                con.Height = (int)a;
                a = System.Convert.ToSingle(mytag[2]) * newx;
                con.Left = (int)a;
                a = System.Convert.ToSingle(mytag[3]) * newy;
                con.Top = (int)a;
                Single currentSize = System.Convert.ToSingle(mytag[4]) * newy;
                con.Font = new Font(con.Font.Name, currentSize, con.Font.Style, con.Font.Unit);
                if (con.Controls.Count > 0)
                    setControls(newx, newy, con);
            }
        }
        private void Form1_Load(object sender, EventArgs e)//当窗口加载时，获取控件大小，我找网上超的
        {
            X = this.Width;
            Y = this.Height;
            setTag(this);
        }
        private void Form1_Resize(object sender, EventArgs e)//当窗口变化时，改变控件大小，我找网上超的
        {
            float newx = (this.Width) / X;
            float newy = (this.Height) / Y;
            setControls(newx, newy, this);
        }
        #endregion
        #region 浮标串口
        private void UpdateTextBoxes()//更新数据
        {
            textBox1.Text = average_waveHeight + "m";
            textBox2.Text = average_period + "s";
            textBox3.Text = one_third_waveHeight + "m";
            textBox4.Text = one_third_period + "s";
            textBox5.Text = one_tenth_waveHeight + "m";
            textBox6.Text = one_tenth_period + "s";
            textBox7.Text = max_waveHeight + "m";
            textBox8.Text = max_period + "s";
        }
        private void SerialPort_init()//串口初始化
        {
            // 获取可用串口列表
            comboBox1.Items.AddRange(SerialPort.GetPortNames());
            if (comboBox1.Items.Count > 0)
                comboBox1.SelectedIndex = 0;

            // 配置默认参数
            serialPort1.BaudRate = 9600;      // 波特率
            serialPort1.DataBits = 8;         // 数据位
            serialPort1.Parity = Parity.None; // 校验位
            serialPort1.StopBits = StopBits.One; // 停止位
            serialPort1.ReadTimeout = 500;    // 读取超时（毫秒）
            serialPort1.WriteTimeout = 500;    // 写入超时
            serialPort1.Encoding = Encoding.GetEncoding("GB2312");//显示中文
        }
        private void RefreshPortList()//更新可用串口
        {
            // 保存当前选中的串口
            string selectedPort = comboBox1.SelectedItem?.ToString();

            // 清空并重新加载所有可用串口
            comboBox1.Items.Clear();
            comboBox1.Items.AddRange(SerialPort.GetPortNames());

            // 恢复之前的选中项（如果仍存在）
            if (!string.IsNullOrEmpty(selectedPort))
            {
                if (comboBox1.Items.Contains(selectedPort))
                    comboBox1.SelectedItem = selectedPort;
                else
                    comboBox1.SelectedIndex = comboBox1.Items.Count > 0 ? 0 : -1;
            }
            else
            {
                comboBox1.SelectedIndex = comboBox1.Items.Count > 0 ? 0 : -1;
            }
        }
        private void button4_Click(object sender, EventArgs e)//刷新串口
        {
            RefreshPortList();
        }
        public bool IsHeaderValid(string input)//校验开头字符
        {
            if (input?.StartsWith("$WAVE") ?? false)//看看开头是不是$WAVE
            {
                return true;
            }
            else { return false; }
        }
        public bool IsEndValid(string input)//校验结尾字符
        {
            bool judge1 = input?.Contains("*") ?? false;//看看这个字符串有没有“*”
            if (judge1)
            {
                return true;
            }
            else 
            { return false; }
        }
        private void ParseWaveData(string rawData)//解析数据
        {
            int index = 0;
            string cleanedData = rawData.Length > 6 ? rawData.Remove(0, 6) : "";//删除$WAVE,
            index = cleanedData.IndexOf('*');//判断字符串中“*”的位置
            cleanedData = index >= 0 ? cleanedData.Substring(0, index) : cleanedData;//保留“*”之前的数据
            string[] fields = cleanedData.Split(',');//分割数据
            //分别赋值
            average_waveHeight = fields[7];
            average_period = fields[8];
            one_third_waveHeight = fields[9];
            one_third_period = fields[10];
            one_tenth_waveHeight = fields[11];
            one_tenth_period = fields[12];
            max_waveHeight = fields[13];
            max_period = fields[14];
            
        }
        private void button1_Click(object sender, EventArgs e)//开启串口按钮
        {        
            if (!serialPort1.IsOpen)
            {
                try
                {
                    serialPort1.PortName = comboBox1.SelectedItem.ToString();
                    serialPort1.Open();
                    comboBox1.Enabled = false;
                    button1.Enabled = false;
                    button2.Enabled = true;
                }
                catch (Exception ex)
                {
                    //是的，这里什么都没有
                }
            }
        }
        private void button2_Click(object sender, EventArgs e)//关闭串口按钮
        {
            if (serialPort1.IsOpen)
            {
                try
                {
                    serialPort1.Close();
                    comboBox1.Enabled = true;
                    button1.Enabled = true;
                    button2.Enabled = false;
                }
                catch (Exception ex)
                {
                    //是的，这里什么都没有
                }
            }
        }
        private void button3_Click(object sender, EventArgs e)//发送数据
        {
            if (serialPort1.IsOpen && !string.IsNullOrEmpty(textBox10.Text))
            {
                try
                {
                    serialPort1.WriteLine(textBox10.Text);
                    textBox10.Clear();
                }
                catch (Exception ex)
                {
                    //是的，这里什么都没有
                }
            }
        }
        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)//接受数据
        {
            // 注意：此事件在非UI线程触发，需用Invoke更新控件
            string receivedData = serialPort1.ReadExisting();
            //这段话是用来截取数据的
            if(IsHeaderValid(receivedData))//判断字符串头是否符合要求
            {
                start_true = true;//开始写字符串以及判断是否需要结束
            }
            if(IsEndValid(receivedData))//判断字符串尾是否复合要求
            {
                end_true = true;//判断结束
            }
            if (start_true)//如果开始的话
            {
                start_add = true;
                if (start_add)
                {
                    data = data + receivedData;
                }
                if (end_true)
                {
                    start_true = false;
                    end_true = false;
                    start_add = false;
                    start_analaze = true;
                }
            }
            else//这里用于避免其他情况下end_true乱触发
            {
                end_true = false;
            }
            if (start_analaze)//开始分析
            {
                start_analaze = false;
                ParseWaveData(data);
                data = "";
            }
            this.Invoke(new Action(() =>
            {
                richTextBox1.AppendText(receivedData);
                UpdateTextBoxes();
            }));
        }
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)//关闭窗口时操作
        {
            if (serialPort1.IsOpen)
                serialPort1.Close();
        }
        private void richTextBox1_TextChanged(object sender, EventArgs e)//自动滚动
        {
            if (is_auto_scroll)
            {
                richTextBox1.SelectionStart = richTextBox1.TextLength;
                richTextBox1.ScrollToCaret();
            }
        }
        private void button5_Click(object sender, EventArgs e)//清除发送区
        {
            textBox10.Text = "";
        }
        private void button6_Click(object sender, EventArgs e)//清除接收区
        {
            richTextBox1.Text = "";
        }
        #endregion
        #region 摄像头
        public void RealDataCallBack(Int32 lRealHandle, UInt32 dwDataType, ref byte pBuffer, UInt32 dwBufSize, IntPtr pUser)
        {
        }
        private void btnLogin_Click(object sender, EventArgs e)
        {
            if (textBoxIP.Text == "" || textBoxPort.Text == "" ||
                textBoxUserName.Text == "" || textBoxPassword.Text == "" )
            {
                MessageBox.Show("请输入本相机IP，端口号，登录名和密码");
                return;
            }
            //设备1
            if (m_lUserID[0] < 0)
            {
                string DVRIPAddress = textBoxIP.Text; //设备IP地址或者域名
                Int16 DVRPortNumber = Int16.Parse(textBoxPort.Text);//设备服务端口号
                string DVRUserName = textBoxUserName.Text;//设备登录用户名
                string DVRPassword = textBoxPassword.Text;//设备登录密码

                CHCNetSDK.NET_DVR_DEVICEINFO_V30 DeviceInfo = new CHCNetSDK.NET_DVR_DEVICEINFO_V30();

                //登录设备 Login the device
                m_lUserID[0] = CHCNetSDK.NET_DVR_Login_V30(DVRIPAddress, DVRPortNumber, DVRUserName, DVRPassword, ref DeviceInfo);
                if (m_lUserID[0] < 0)
                {
                    iLastErr[0] = CHCNetSDK.NET_DVR_GetLastError();
                    str = "海康相机连接失败, 错误号= " + iLastErr[0]; //登录失败，输出错误号
                    MessageBox.Show(str);
                    return;
                }
                else
                {
                    //登录成功
                    MessageBox.Show("海康相机连接成功!");
                    /*btnLogin.Text = "断开连接";*/

                }

            }
            else
            {
                //注销登录 Logout the device
                if (m_lRealHandle[0] >= 0)
                {
                    MessageBox.Show("请先停止预览");
                    return;
                }

                if (!CHCNetSDK.NET_DVR_Logout(m_lUserID[0]))
                {
                    iLastErr[0] = CHCNetSDK.NET_DVR_GetLastError();
                    str = "断开连接失败, 错误号= " + iLastErr[0];
                    MessageBox.Show(str);
                    return;
                }
                m_lUserID[0] = -1;
                /* btnLogin.Text = "连接";*/
            }
            return;
        }
        private void BtnLogin2_Click(object sender, EventArgs e)
        {
            if (textBoxIP2.Text == "" || textBoxPort2.Text == "" ||
                textBoxUserName2.Text == "" || textBoxPassword2.Text == "")
            {
                MessageBox.Show("请输入本相机IP，端口号，登录名和密码");
                return;
            }
            //设备2
            if (m_lUserID[1] < 0)
            {
                string DVRIPAddress2 = textBoxIP2.Text; //设备IP地址或者域名
                Int16 DVRPortNumber2 = Int16.Parse(textBoxPort2.Text);//设备服务端口号
                string DVRUserName2 = textBoxUserName2.Text;//设备登录用户名
                string DVRPassword2 = textBoxPassword2.Text;//设备登录密码

                CHCNetSDK.NET_DVR_DEVICEINFO_V30 DeviceInfo2 = new CHCNetSDK.NET_DVR_DEVICEINFO_V30();

                //登录设备 Login the device
                m_lUserID[1] = CHCNetSDK.NET_DVR_Login_V30(DVRIPAddress2, DVRPortNumber2, DVRUserName2, DVRPassword2, ref DeviceInfo2);
                if (m_lUserID[1] < 0)
                {
                    iLastErr[1] = CHCNetSDK.NET_DVR_GetLastError();
                    str = "Sionyx相机连接失败, 错误号= " + iLastErr[1]; //登录失败，输出错误号
                    MessageBox.Show(str);
                    return;
                }
                else
                {
                    //登录成功
                    MessageBox.Show("Sionyx相机连接成功!");
                    btnLogin.Text = "断开连接";

                }

            }
            else
            {
                //注销登录 Logout the device
                if (m_lRealHandle[1] >= 0)
                {
                    MessageBox.Show("请先停止预览");
                    return;
                }

                if (!CHCNetSDK.NET_DVR_Logout(m_lUserID[1]))
                {
                    iLastErr[1] = CHCNetSDK.NET_DVR_GetLastError();
                    str = "断开连接失败, 错误号= " + iLastErr[1];
                    MessageBox.Show(str);
                    return;
                }
                m_lUserID[1] = -1;
                btnLogin.Text = "连接";
            }
            return;
        }
        private void btnPreview_Click(object sender, EventArgs e)
        {
            if (m_lUserID[0] < 0)
            {
                MessageBox.Show("请先连接海康相机后再进行操作");
                return;
            }

            if (m_lRealHandle[0] < 0)
            {
                //预览窗口1相机 RealPlay window
                CHCNetSDK.NET_DVR_PREVIEWINFO lpPreviewInfo = new CHCNetSDK.NET_DVR_PREVIEWINFO();
                lpPreviewInfo.hPlayWnd = RealPlayWnd.Handle;//预览窗口
                lpPreviewInfo.lChannel = Int16.Parse(textBoxChannel.Text);//预览设备的通道
                lpPreviewInfo.dwStreamType = 0;//码流类型：0-主码流，1-子码流，2-码流3，3-码流4，以此类推
                lpPreviewInfo.dwLinkMode = 0;//连接方式：0- TCP方式，1- UDP方式，2- 多播方式，3- RTP方式，4-RTP/RTSP，5-RSTP/HTTP 
                lpPreviewInfo.bBlocked = true; //0- 非阻塞取流，1- 阻塞取流
                lpPreviewInfo.dwDisplayBufNum = 15; //播放库播放缓冲区最大缓冲帧数

                CHCNetSDK.REALDATACALLBACK RealData = new CHCNetSDK.REALDATACALLBACK(RealDataCallBack);//预览实时流回调函数
                IntPtr pUser = new IntPtr();//用户数据

                //打开预览 Start live view 
                m_lRealHandle[0] = CHCNetSDK.NET_DVR_RealPlay_V40(m_lUserID[0], ref lpPreviewInfo, null/*RealData*/, pUser);

                if (m_lRealHandle[0] < 0)
                {
                    iLastErr[0] = CHCNetSDK.NET_DVR_GetLastError();
                    str = "开启海康相机预览失败, 错误号" + iLastErr[0]; //预览失败，输出错误号
                    MessageBox.Show(str);
                    return;
                }
                else
                {
                    //预览成功
                    btnPreview.Text = "停止预览";
                }
            }
            else
            {
                //停止预览 Stop live view 
                if (!CHCNetSDK.NET_DVR_StopRealPlay(m_lRealHandle[0]))
                {
                    iLastErr[0] = CHCNetSDK.NET_DVR_GetLastError();
                    str = "停止海康相机预览失败, 错误号" + iLastErr;
                    MessageBox.Show(str);
                    return;
                }
                m_lRealHandle[0] = -1;
                btnPreview.Text = "开启预览";

            }
            return;
        }
        private void btnPreview2_Click(object sender, EventArgs e)
        {
            if (m_lUserID[1] < 0)
            {
                MessageBox.Show("请先连接Sionyx相机后再进行操作");
                return;
            }

            if (m_lRealHandle[1] < 0)
            {
                //预览窗口1相机 RealPlay window
                CHCNetSDK.NET_DVR_PREVIEWINFO lpPreviewInfo = new CHCNetSDK.NET_DVR_PREVIEWINFO();
                lpPreviewInfo.hPlayWnd = RealPlayWnd2.Handle;//预览窗口
                lpPreviewInfo.lChannel = Int16.Parse(textBoxChannel2.Text);//预览设备的通道
                lpPreviewInfo.dwStreamType = 0;//码流类型：0-主码流，1-子码流，2-码流3，3-码流4，以此类推
                lpPreviewInfo.dwLinkMode = 0;//连接方式：0- TCP方式，1- UDP方式，2- 多播方式，3- RTP方式，4-RTP/RTSP，5-RSTP/HTTP 
                lpPreviewInfo.bBlocked = true; //0- 非阻塞取流，1- 阻塞取流
                lpPreviewInfo.dwDisplayBufNum = 15; //播放库播放缓冲区最大缓冲帧数

                CHCNetSDK.REALDATACALLBACK RealData = new CHCNetSDK.REALDATACALLBACK(RealDataCallBack);//预览实时流回调函数
                IntPtr pUser = new IntPtr();//用户数据

                //打开预览 Start live view 
                m_lRealHandle[1] = CHCNetSDK.NET_DVR_RealPlay_V40(m_lUserID[1], ref lpPreviewInfo, null/*RealData*/, pUser);

                if (m_lRealHandle[1] < 0)
                {
                    iLastErr[1] = CHCNetSDK.NET_DVR_GetLastError();
                    str = "开启预览失败, 错误号" + iLastErr[1]; //预览失败，输出错误号
                    MessageBox.Show(str);
                    return;
                }
                else
                {
                    //预览成功
                    btnPreview2.Text = "停止预览";
                }
            }
            else
            {
                //停止预览 Stop live view 
                if (!CHCNetSDK.NET_DVR_StopRealPlay(m_lRealHandle[1]))
                {
                    iLastErr[1] = CHCNetSDK.NET_DVR_GetLastError();
                    str = "停止预览失败, 错误号" + iLastErr[1];
                    MessageBox.Show(str);
                    return;
                }
                m_lRealHandle[1] = -1;
                btnPreview2.Text = "开启预览";

            }
            return;
        }
        private void btnJPEG_Click(object sender, EventArgs e)
        {
            System.DateTime currentTime = new System.DateTime();
            currentTime = System.DateTime.Now;
            string sJpegPicFileName;
            //图片保存路径和文件名 the path and file name to save
            sJpegPicFileName = currentTime.Year + "_" + currentTime.Month + "_" +
                currentTime.Day + "_" + currentTime.Hour + "_" + currentTime.Minute +
                "_" + currentTime.Second + "-" + "JPEG_test.jpg";

            int lChannel = Int16.Parse(textBoxChannel.Text); //通道号 Channel number

            CHCNetSDK.NET_DVR_JPEGPARA lpJpegPara = new CHCNetSDK.NET_DVR_JPEGPARA();
            lpJpegPara.wPicQuality = 0; //图像质量 Image quality
            lpJpegPara.wPicSize = 0xff; //抓图分辨率 Picture size: 2- 4CIF，0xff- Auto(使用当前码流分辨率)，抓图分辨率需要设备支持，更多取值请参考SDK文档

            //JPEG抓图 Capture a JPEG picture
            if (!CHCNetSDK.NET_DVR_CaptureJPEGPicture(m_lUserID[0], lChannel, ref lpJpegPara, sJpegPicFileName))
            {
                iLastErr[0] = CHCNetSDK.NET_DVR_GetLastError();
                str = "JPEG抓图失败，错误号" + iLastErr[0];
                MessageBox.Show(str);
                return;
            }
            else
            {
                str = "JPEG抓图成功，文件名为" + sJpegPicFileName;
                MessageBox.Show(str);
            }
            return;
        }
        private void btnBMP_Click(object sender, EventArgs e)
        {
            System.DateTime currentTime = new System.DateTime();
            currentTime = System.DateTime.Now;
            string sBmpPicFileName;
            //图片保存路径和文件名 the path and file name to save
            sBmpPicFileName = currentTime.Year + "_" + currentTime.Month + "_" +
                currentTime.Day + "_" + currentTime.Hour + "_" + currentTime.Minute +
                "_" + currentTime.Second + "-" + "BMP_test.bmp";

            //BMP抓图 Capture a BMP picture
            if (!CHCNetSDK.NET_DVR_CapturePicture(m_lRealHandle[1], sBmpPicFileName))
            {
                iLastErr[1] = CHCNetSDK.NET_DVR_GetLastError();
                str = "BMP抓图失败, 错误号" + iLastErr[1];
                MessageBox.Show(str);
                return;
            }
            else
            {
                str = "BMP抓图成功，图片名称为" + sBmpPicFileName;
                MessageBox.Show(str);
            }
            return;
        }
        private void btnRecord_Click(object sender, EventArgs e)
        {
            System.DateTime currentTime = new System.DateTime();
            currentTime = System.DateTime.Now;
            //录像保存路径和文件名 the path and file name to save
            string sVideoFileName;
            sVideoFileName = currentTime.Year + "_" + currentTime.Month + "_" +
                currentTime.Day + "_" + currentTime.Hour + "_" + currentTime.Minute +
                "_" + currentTime.Second + "-" + "海康录像.mp4";

            if (m_bRecord[0] == false)
            {
                //强制I帧 Make a I frame
                int lChannel = Int16.Parse(textBoxChannel.Text); //通道号 Channel number
                CHCNetSDK.NET_DVR_MakeKeyFrame(m_lUserID[0], lChannel);

                //开始录像 Start recording
                if (!CHCNetSDK.NET_DVR_SaveRealData(m_lRealHandle[0], sVideoFileName))
                {
                    iLastErr[0] = CHCNetSDK.NET_DVR_GetLastError();
                    str = "海康录像保存失败，错误号" + iLastErr[0];
                    MessageBox.Show(str);
                    return;
                }
                else
                {
                    btnRecord.Text = "停止录像";
                    m_bRecord[0] = true;
                }
            }
            else
            {
                //停止录像 Stop recording
                if (!CHCNetSDK.NET_DVR_StopSaveRealData(m_lRealHandle[0]))
                {
                    iLastErr[0] = CHCNetSDK.NET_DVR_GetLastError();
                    str = "停止海康录像失败，错误号" + iLastErr;
                    MessageBox.Show(str);
                    return;
                }
                else
                {
                    str = "保存海康录像成功，文件名为" + sVideoFileName;
                    MessageBox.Show(str);
                    btnRecord.Text = "开始录像";
                    m_bRecord[0] = false;
                }
            }
            return;
        }
        private void btnRecord2_Click(object sender, EventArgs e)
        {
            System.DateTime currentTime = new System.DateTime();
            currentTime = System.DateTime.Now;
            //录像保存路径和文件名 the path and file name to save
            string sVideoFileName;
            sVideoFileName = currentTime.Year + "_" + currentTime.Month + "_" +
                currentTime.Day + "_" + currentTime.Hour + "_" + currentTime.Minute +
                "_" + currentTime.Second + "-" + "夜视录像.mp4";

            if (m_bRecord[1] == false)
            {
                //强制I帧 Make a I frame
                int lChannel = Int16.Parse(textBoxChannel2.Text); //通道号 Channel number
                CHCNetSDK.NET_DVR_MakeKeyFrame(m_lUserID[1], lChannel);

                //开始录像 Start recording
                if (!CHCNetSDK.NET_DVR_SaveRealData(m_lRealHandle[1], sVideoFileName))
                {
                    iLastErr[1] = CHCNetSDK.NET_DVR_GetLastError();
                    str = "夜视录像保存失败，错误号" + iLastErr[1];
                    MessageBox.Show(str);
                    return;
                }
                else
                {
                    btnRecord2.Text = "停止录像";
                    m_bRecord[1] = true;
                }
            }
            else
            {
                //停止录像 Stop recording
                if (!CHCNetSDK.NET_DVR_StopSaveRealData(m_lRealHandle[1]))
                {
                    iLastErr[1] = CHCNetSDK.NET_DVR_GetLastError();
                    str = "停止夜视录像失败，错误号" + iLastErr[1];
                    MessageBox.Show(str);
                    return;
                }
                else
                {
                    str = "保存夜视录像成功，文件名为" + sVideoFileName;
                    MessageBox.Show(str);
                    btnRecord2.Text = "开始录像";
                    m_bRecord[1] = false;
                }
            }
            return;
        }
        private void btnExit_Click(object sender, EventArgs e)
        {
            //停止
            Dispose(true);
            Application.Exit();
        }
        private void btnPTZ_Click(object sender, EventArgs e)
        {
            PTZControl dlg = new PTZControl();
            dlg.m_lUserID = m_lUserID[0];
            dlg.m_lChannel = 1;
            dlg.m_lRealHandle = m_lRealHandle[0];
            dlg.ShowDialog();
        }





        #endregion

        private void wind_water_Click(object sender, EventArgs e)
        {
            Form2 form2 = new Form2();
            form2.ShowDialog();
        }

        private void textBoxIP_TextChanged(object sender, EventArgs e)
        {

        }
    }
}
